﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


namespace Better
{
    public static class TempData
    {
        //Collection
        public static TempDataCollection Collection = new TempDataCollection();


        //Methods
        public static void HandleEndRequest()
        {
            Collection.Purge();
        }
    }


    public class TempDataCollection
    {
        //Indexer
        public object this[string key]
        {
            get
            {
                try
                {
                    return GetCollection[key][0];
                }
                catch
                {
                    return null;
                }
            }
            set
            {
                GetCollection[key] = new object[] { value, 0 };
            }
        }


        //Properties
        public int Count
        {
            get
            {
                return this.GetCollection.Count;
            }
        }

        protected Dictionary<string, object[]> GetCollection
        {
            get
            {
                if (HttpContext.Current.Session["BetterTempDataCollection"] == null)
                {
                    HttpContext.Current.Session["BetterTempDataCollection"] = new Dictionary<string, object[]>();
                }

                return (Dictionary<string, object[]>)HttpContext.Current.Session["BetterTempDataCollection"];
            }
        }


        //Methods
        public void Purge()
        {
            List<string> keysToRemove = new List<string>();

            for (int i = 0; i < GetCollection.Count; i++)
            {
                KeyValuePair<string, object[]> el = GetCollection.ElementAt(i);

                if ((int)el.Value[1] > 0)
                {
                    keysToRemove.Add(el.Key);
                }
                else
                {
                    el.Value[1] = ((int)el.Value[1]) + 1;
                }
            }

            foreach(string s in keysToRemove)
            {
                GetCollection.Remove(s);
            }
        }

        public void Keep(string Key)
        {
            try
            {
                GetCollection[Key][1] = 0;
            }
            catch { }
        }
    }
}